package concurrent;

/**
 * @File Info: leetcode -- <ThreeThread>
 * @Author: 18362
 * @Create: 2022-03-14 12:40:06 星期一
 */


/**
 * 三个线程交替打印1A、2B、3C...
 */
public class ThreeThread {

    public static volatile int i = 0;
    public static int cnt = 26;
    public static Object monitor = new Object();

    static class MyThread extends Thread {

        private int k;

        public MyThread(String name, int k) {
            super(name);
            this.k = k;
        }

        @Override
        public void run() {
            synchronized (monitor) {
                try {
                    while (true) {
                        while (i % 3 != k && i < cnt) {
                            monitor.wait();
                        }

                        if (i >= cnt) {
                            monitor.notifyAll();
                            break;
                        }

                        char c = (char) (i + 'A');
                        System.out.println(getName() + ": " + (i+1) + "" + c);
                        i++;
                        monitor.notifyAll();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        new MyThread("thread-1", 0).start();
        new MyThread("thread-2", 1).start();
        new MyThread("thread-3", 2).start();
    }
}
